<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="css/reset.css">
    <style>
        .box {
            width: 300px;
            height: 350px;
            padding: 20px 50px;
            border-radius: 5px;
            background-color: gainsboro;
        }

        .box p {
            width: 200px;
            height: 40px;
            margin-bottom: 20px;
            border-radius: 5px;
            text-align: center;
            border: 1px solid gainsboro;
        }

        .box p input {
            width: 100%;
            height: 100%;
            border-radius: 5px;
            padding: 0 10px;
            
        }
    </style>
</head>
<body>
    <div class="box">
        <p>注册新账号</p>
        <p>
            <input type="text" placeholder="请输入账号">
        </p>
        <p>
            <input type="password" placeholder="请输入密码">
        </p>
        <p>
            <input type="password" placeholder="确认密码">
        </p>
        <p>
            <input type="button" value="注册">
        </p>
    </div>
</body>
</html>
<script>
        function objToSearchString(obj) {
        let str=''
        for (const key in obj) {
            str += `${key}=${obj[key]}&`
        }
        return str.slice(0,str.length-1)
    }
    // 封装ajax
    function ajax(method, url, params, cb) {
        let xhr = new XMLHttpRequest()

        xhr.open(method, method == 'get' ? url + '?' + objToSearchString(params) : url)

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                cb(JSON.parse(xhr.responseText))
            }
        }
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(method == 'get' ? null : objToSearchString(params))
    }
    let inputs=document.querySelectorAll('input')
    inputs[3].onclick=function(){
        if (inputs[0].value && inputs[1].value && inputs[2].value) {
            if (/^1[3-9]\d{9}$/.test(inputs[0].value) && /^[0-9]{4}$/.test(inputs[1].value)) {
                if (inputs[1].value == inputs[2].value) {
                    ajax('get','https://yantianfeng.com/api/register',{username:inputs[0].value,password:inputs[1].value},function(data){
                        console.log(data);
                    })
                } else {
                    alert('两次密码输入不一致')
                }
            } else {
                alert('请输入正确的账号和密码')
            }
        } else {
            alert('账号密码不能为空')
        }
    }
</script>